#!/bin/bash
# mvn clean package docker:build 
appName=$1
appPort=$2
containerPort=$appPort
appNameB="$appName"B
containerPortB=$[$appPort+1]
containerId="1"
containerIdB="1" 
rmImages="1"
containerId=`docker ps -a -q --no-trunc --filter name=^/"$appName"$`
containerIdB=`docker ps -a -q --no-trunc --filter name=^/"$appNameB"$`
if [ -n "$containerId" ]
then
    echo "已有容器："
    echo "$containerId"
fi
if [ -n "$containerIdB" ]
then
    echo "已有容器B："
    echo "$containerIdB"
fi
if [ -z "$containerId" ] && [ -z "$containerIdB" ];
then
    echo "当前不存在该容器，直接进行启动该操作-------------------------------------"
    docker run -m 600M -p "$containerPort":"$appPort" -d --name "$appName" com.infohold/"$appName":latest
elif [ -n "$containerId" ] && [ -z "$containerIdB" ];
then
    echo "当前已存在容器1，先启动容器2，1m后进行容器删除--------------------------------------"
    docker run -m 600M -p "$containerPortB":"$appPort" -d --name "$appNameB" com.infohold/"$appName":latest
    sleep 1m
    docker stop "$containerId"
    docker rm "$containerId"
elif [ -z "$containerId" ] && [ -n "$containerIdB" ];
then
    echo "当前已存在容器2，先启动容器1，1m后进行容器删除-------------------------------------"
    docker run -m 600M -p "$containerPort":"$appPort" -d --name "$appName" com.infohold/"$appName":latest
    sleep 1m
    docker stop "$containerIdB"
    docker rm "$containerIdB"
elif [ -z "$containerId" ] && [ -z "$containerIdB" ];
then
    echo "当前已存在两个容器，先停止容器1，重启容器1，1m后进行容器2的删除-------------------------------------"
    docker stop "$containerId"
    docker rm "$containerId"
    docker run -m 600M -p "$containerPort":"$appPort" -d --name "$appName" com.infohold/"$appName":latest
    sleep 1m
    docker stop "$containerIdB"
    docker rm "$containerIdB"
elif [ "$containerId" == "1" ] || [ "$containerIdB" == "1" ];
then
    echo "查询的信息有误，执行默认操作-------------------------------------"
fi
rmImages=`docker images -f "dangling=true" -q`
if [ -z "$rmImages" ] || [ "$rmImages" == "1" ]
then
    echo "未查询到需要删除的镜像"
else
    echo "删除镜像-------------------------------------"
    docker rmi $(docker images -f "dangling=true" -q)
fi
